<?php
// -----------------------------------------------------------------------------
// include
// -----------------------------------------------------------------------------

include "config/config.php";
include "auth.php";
include "DBManager.php";

// -----------------------------------------------------------------------------
// 数据库相关设置
// -----------------------------------------------------------------------------

$db = new DBManager("sqlite:" . $dbPath);

// -----------------------------------------------------------------------------

if (!isset($_GET['from'])) {
    exit("需要指定完整的参数。");
}

$from = htmlspecialchars($_GET['from']);

// -----------------------------------------------------------------------------

$content = "";

$hiddenHtml = <<<BBB
    <input type="hidden" id="inputFrom" name="from" value="$from">
BBB;

switch ($from) {
    case "daily":
        $content = $db->readFromDaily();
        break;
    case "weekly":
        if (!isset($_GET['dayOfWeek'])) {
            exit("参数不完整。");
        }
        $dayOfWeek = htmlspecialchars($_GET['dayOfWeek']);
        $content = $db->readFromWeekly($dayOfWeek);

        $hiddenHtml .= <<<BBB
            <input type="hidden" name="dayOfWeek" value="$dayOfWeek">
        BBB;

        break;
    case "monthly":
        if (!isset($_GET['dayOfMonth'])) {
            exit("参数不完整。");
        }
        $dayOfMonth = htmlspecialchars($_GET['dayOfMonth']);
        $content = $db->readFromMonthly($dayOfMonth);

        $hiddenHtml .= <<<BBB
            <input type="hidden" name="dayOfMonth" value="$dayOfMonth">
        BBB;

        break;
    case "monthlyLunar":
        if (!isset($_GET['dayOfMonth'])) {
            exit("参数不完整。");
        }
        $dayOfMonth = htmlspecialchars($_GET['dayOfMonth']);
        $content = $db->readFromMonthlyLunar($dayOfMonth);

        $hiddenHtml .= <<<BBB
            <input type="hidden" name="dayOfMonth" value="$dayOfMonth">
        BBB;

        break;
    case "yearly":
        if (!isset($_GET['monthAndDay'])) {
            exit("参数不完整。");
        }
        $monthAndDay = htmlspecialchars($_GET['monthAndDay']);
        $content = $db->readFromYearly($monthAndDay);

        $hiddenHtml .= <<<BBB
            <input type="hidden" name="monthAndDay" value="$monthAndDay">
        BBB;

        break;
    case "yearlyLunar":
        if (!isset($_GET['monthAndDay'])) {
            exit("参数不完整。");
        }
        $monthAndDay = htmlspecialchars($_GET['monthAndDay']);
        $content = $db->readFromYearlyLunar($monthAndDay);

        $hiddenHtml .= <<<BBB
            <input type="hidden" name="monthAndDay" value="$monthAndDay">
        BBB;

        break;
    case "specificDate":
        if (!isset($_GET['date'])) {
            exit("参数不完整。");
        }
        $date = htmlspecialchars($_GET['date']);
        $content = $db->readFromSpecificDate($date);

        $hiddenHtml .= <<<BBB
            <input type="hidden" name="date" value="$date">
        BBB;
}

// 由于 HTML 标准，textarea 中的第一个换行符会被剥离。注意是被剥离，不是被隐藏。保存的时候，这个换行也会丢失。
// 这段代码使得 textarea 中显示的数据与保存时的数据完全一致
// 保存的时候，textarea 起首能看见多少换行，就保存多少换行，不会导致换行越来越多
if (!empty($content)) {
    if (bin2hex($content[0]) == "0d") {
        // 这里有些小疑惑：
        // 0d 对应的是 \r, 0a 对应的是 \n
        // windows 上的换行符号是 \r\n，linux 上的换行符号是 \n
        // 理论上来说，程序在 linux 服务器上跑，这里取得的值应该是 0a 才对呀，但是实际上是 0d
        $content = PHP_EOL . $content;
    }
}

// -----------------------------------------------------------------------------

$todoTemplateId = 1;

$todoTemplate = $db->getTodoTemplateById($todoTemplateId);
if (!$todoTemplate) {
    $todoTemplate = "";
}

// -----------------------------------------------------------------------------
?>
<html lang="zh">

<head>
    <meta charset="utf-8">
    <title>编辑</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <link rel="stylesheet" href="resources/bootstrap-5.2.0-beta1-dist/css/bootstrap.min.css">
</head>

<body>

<!-- ----------------------------------------------------------------------- -->

<script src="resources/bootstrap-5.2.0-beta1-dist/js/bootstrap.min.js"></script>
<script src="resources/jQuery/jquery-3.5.1.js"></script>
<?php include "globalNavbar.php"; ?>

<!-- ----------------------------------------------------------------------- -->

<div class="container container-fluid mt-3 mb-5">

    <!-- 导航栏 开始 -->
    <div class="mt-3">
        <nav style="--bs-breadcrumb-divider: '>';" aria-label="breadcrumb">
            <ol class="breadcrumb">
                <li class="breadcrumb-item"><a class="text-decoration-none" href="<?php echo $homepage; ?>">首页</a></li>
                <li class="breadcrumb-item active">编辑</li>
            </ol>
        </nav>
    </div>
    <!-- 导航栏 结束 -->

    <form class="mt-0" action="editFormAction.php" method="post" id="myForm">

        <div>
            <?php echo $hiddenHtml; ?>
        </div>

        <div>
            <textarea name="content"
                id="inputContent"
                class="form-control"
                autofocus
                cols="30"
                rows="15"><?php echo $content; ?></textarea>
        </div>

        <div class="mt-3 d-flex">
            <div class="w-100">
                <button id="btnSubmit" type="button" class="btn btn-outline-primary">保存</button>
                <button id="btnClear" type="button" class="btn btn-outline-secondary">清空</button>
            </div>
            <div class="flex-shrink-0">
                <button id="btnShowTemplate" type="button" class="btn btn-outline-warning">模板</button>
            </div>
        </div>

    </form>
</div>

<!-- ----------------------------------------------------------------------- -->

<!-- modal 待办模板 开始 -->
<div class="modal fade" id="modalTodoTemplate" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="">模板</h1>
                <button id="btnCloseModalTodoTemplate" type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <div class="modal-body">
                <div>
                    <textarea name="todoTemplate"
                        id="inputTodoTemplate"
                        class="form-control"
                        cols="30"
                        rows="16"
                        placeholder="使用前，请先编辑模板。"
                        require><?php echo $todoTemplate; ?></textarea>
                </div>
                <div class="mt-3 d-flex">
                    <div class="w-100">
                        <button id="btnSaveTemplate" type="button" class="btn btn-outline-primary">保存</button>
                        <button id="btnResetTemplate" type="reset" class="btn btn-outline-secondary">清空</button>
                    </div>
                    <div class="flex-shrink-0">
                        <button id="btnInsertTemplate" type="button" class="btn btn-outline-warning">插入</button>
                    </div>
                </div>
            </div>

        </div>
    </div>
</div>
<!-- modal 待办模板 结束 -->

<!-- ----------------------------------------------------------------------- -->

<!--消息弹窗 开始-->
<div aria-live="polite" aria-atomic="true" class="position-relative">
    <div class="toast-container position-fixed top-0 start-50 translate-middle-x">

        <div id="toastOne" class="toast" role="alert" aria-live="assertive" aria-atomic="true">
            <div class="toast-header bg-info">
                <strong class="me-auto">提示</strong>
                <button type="button" class="btn-close" data-bs-dismiss="toast" aria-label="Close"></button>
            </div>
            <div class="toast-body bg-white">
                <p id="msgContent">数据保存成功！</p>
            </div>
        </div>

    </div>
</div>
<!--消息弹窗 结束-->

<!-- ----------------------------------------------------------------------- -->
<script src="resources/jQuery/jquery-3.5.1.js"></script>
<script src="resources/bootstrap-5.2.0-beta1-dist/js/bootstrap.min.js"></script>
<!-- ----------------------------------------------------------------------- -->

<!--全局变量-->
<script>
    // 记录初始 template，用于判断是否修改了 template，以决定是否要「保存」。
    let oldTodoTemplate = "";
</script>

<!-- ----------------------------------------------------------------------- -->

<!-- 待办模板相关 -->
<script>

    // 弹出模板对话框
    $("#btnShowTemplate").on("click", function() {

        oldTodoTemplate = $("#inputTodoTemplate").val()

        const myModal = new bootstrap.Modal($("#modalTodoTemplate"), {
            backdrop: 'static',
            keyboard: true
        })
        myModal.show()

    })

    // 保存模板
    $("#btnSaveTemplate").on("click", function() {
        saveTodoTemplate()
    })

    // 清空模板
    $("#btnResetTemplate").on("click", function() {
        $("#inputTodoTemplate").val("")
        $("#inputTodoTemplate").focus()
    })

    // 使用模板
    $("#btnInsertTemplate").on("click", function() {

        // 使用模板
        const todoTemplate = $("#inputTodoTemplate").val();
        $("#inputContent").val(todoTemplate)
        $("#btnCloseModalTodoTemplate").click()

        // 点击「使用」时，自动执行「保存」
        // 可能有时候作了修改，会忘记「保存」，而直接点击「使用」
        saveTodoTemplate()

    })

</script>

<script>

    // 修改模板
    function saveTodoTemplate() {

        const todoTemplate = $("#inputTodoTemplate").val();

        if (todoTemplate !== oldTodoTemplate) {

            // 修改模板
            const url = "ajax/writeToTodoTemplate.php";
            const id = "<?php echo $todoTemplateId; ?>";
            const content = $("#inputTodoTemplate").val();

            $.ajax({
                    method: "POST",
                    url: url,
                    async: true,
                    data: {
                        id: id,
                        content: content
                    }
                })
                .done(function(data) {

                    // 将保存后的模板，标记为 oldTodoTemplate
                    // 这样一来，点击「保存」后再点击「使用」，就不会再次保存了。
                    oldTodoTemplate = todoTemplate

                    $("#msgContent").text(data)
                    $("#toastHeader").attr("class", "toast-header bg-info")
                    const toast = new bootstrap.Toast(toastOne, {
                        "delay": 1000
                    })
                    toast.show()

                })
                .fail(function(jqXHR, textStatus) {
                    alert("保存失败！")
                });

        }

    }

</script>

<!-- ----------------------------------------------------------------------- -->

<!-- 按钮事件处理 -->
<script>

    $("#btnSubmit").on("click", function() {

        var url = "editFormAction.php";

        $.post(url, $("#myForm").serialize())
            .done(function(data) {
                $("#msgContent").text(data)
                const toast = new bootstrap.Toast(toastOne, {
                    "delay": 1000
                })
                toast.show()
            })
            .fail(function() {
                $("#msgContent").text("请求失败！")
                const toast = new bootstrap.Toast(toastOne, {
                    "delay": 1000
                })
                toast.show()
            })

    })

    $("#btnClear").on("click", function() {
        $("#inputContent").val("")
        $("#inputContent").focus()
    })

</script>

<!-- ----------------------------------------------------------------------- -->

<script>
    // 在主编辑框中编辑时，按下 ctrl + s 保存编辑内容。
    // 参考资料：https://stackoverflow.com/questions/93695/best-cross-browser-method-to-capture-ctrls-with-jquery
    $(document).on('keydown', '#inputContent', function(event) {
        if (event.ctrlKey || event.metaKey) {
            switch ((event.key).toLowerCase()) {
                case 's':
                    event.preventDefault();
                    $("#btnSubmit").click();
            }
        }
    });

    // 编辑「待办模板」时，按下 ctrl + s 保存模板。
    $(document).on('keydown', '#inputTodoTemplate', function(event) {
        if (event.ctrlKey || event.metaKey) {
            switch ((event.key).toLowerCase()) {
                case 's':
                    event.preventDefault();
                    $("#btnSaveTemplate").click();
            }
        }
    });
</script>

<!-- ----------------------------------------------------------------------- -->

<script>
    var formEdited = false;

    // 监听用户是进行了输入操作
    $(".form-control").keydown(function() {
        formEdited = true;
    });

    // 页面刷新或关闭前弹窗警告
    $(window).on('beforeunload', function() {
        if (formEdited == true) {
            return "Are you sure you want to leave?";
        }
    });

    // 点击按钮提交表单刷新页面时不弹窗警告
    $('#btnSubmit').on("click", function() {
        $(window).off('beforeunload');
    });
</script>

<!-- ----------------------------------------------------------------------- -->

</body>

</html>
